package com.t.bricks.bussiness.util.wechat.subscribeaccount;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.t.bricks.model.Log;

/**
 * 消息解析工具类
 */
public class MessageUtil {

	/**
	 * 将xml内容解析成map
	 * @param request
	 * @return
	 */
	public static Map<String, String> xmlToMap(HttpServletRequest request) {
		Map<String, String> map = new HashMap<>();
		SAXReader reader = new SAXReader();
		
		try (
				InputStream in = request.getInputStream();
		) {
			Document doc = reader.read(in);
			Element root = doc.getRootElement();
			@SuppressWarnings("unchecked")
			List<Element> list = root.elements();
			for (Element element : list) {
				map.put(element.getName(), element.getText());
			}
		} catch (IOException e) {
			Log.error("读取流信息发生异常:", e.getMessage());
		} catch (DocumentException e) {
			Log.error("解析信息发生异常:", e.getMessage());
		} catch (Exception e) {
			Log.error("发生不可预知的异常:", e.getMessage());
		}
		
		return map;
	}
	
	/**
	 * 将xml内容解析成map
	 * @param requestInputStream
	 * @return
	 */
	public static Map<String, String> xmlToMap(String requestInputStream) {
		Map<String, String> map = new HashMap<>();
		if (null == requestInputStream || "".equals(requestInputStream)) {
			return map;
		}

		SAXReader reader = new SAXReader();

		try (
				InputStream in = new ByteArrayInputStream(requestInputStream.getBytes());
		) {
			Document doc = reader.read(in);
			Element root = doc.getRootElement();
			@SuppressWarnings("unchecked")
			List<Element> list = root.elements();
			for (Element element : list) {
				map.put(element.getName(), element.getText());
			}
		} catch (DocumentException e) {
			Log.error("解析信息发生异常:", e.getMessage());
		} catch (Exception e) {
			Log.error("发生不可预知的异常:", e.getMessage());
		}
		
		return map;
	}
	
}
